package com.ruoyi.patrol.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.patrol.domain.PtCheckAnswer;
import com.ruoyi.patrol.domain.PtCheckQuestion;
import com.ruoyi.patrol.domain.PtCheckRecord;
import com.ruoyi.patrol.domain.PtCheckType;
import com.ruoyi.patrol.service.IPtCheckAnswerService;
import com.ruoyi.patrol.service.IPtCheckRecordService;
import com.ruoyi.patrol.service.IPtCheckTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.List;

/**
 * 专项检查类型Controller
 *
 * @author Du
 * @date 2023-11-18
 */
@RestController
@RequestMapping("/patrol/checkType")
public class PtCheckTypeController extends BaseController {
    @Autowired
    private IPtCheckTypeService ptCheckTypeService;

    @Autowired
    private IPtCheckRecordService ptCheckRecordService;

    @Autowired
    private IPtCheckAnswerService ptCheckAnswerService;

    /**
     * 查询专项检查类型列表
     */
    @PreAuthorize("@ss.hasPermi('patrol:checkType:list')")
    @GetMapping("/list")
    public TableDataInfo list(PtCheckType ptCheckType) {
        startPage();
        List<PtCheckType> list = ptCheckTypeService.selectPtCheckTypeList(ptCheckType);
        return getDataTable(list);
    }

    /**
     * 导出专项检查类型列表
     */
    @PreAuthorize("@ss.hasPermi('patrol:checkType:export')")
    @Log(title = "专项检查类型", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(PtCheckType ptCheckType) {
        List<PtCheckType> list = ptCheckTypeService.selectPtCheckTypeList(ptCheckType);
        ExcelUtil<PtCheckType> util = new ExcelUtil<PtCheckType>(PtCheckType.class);
        return util.exportExcel(list, "checkType");
    }

    /**
     * 获取专项检查类型详细信息
     */
    @PreAuthorize("@ss.hasPermi('patrol:checkType:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(ptCheckTypeService.selectPtCheckTypeById(id));
    }

    /**
     * 新增专项检查类型
     */
    @PreAuthorize("@ss.hasPermi('patrol:checkType:add')")
    @Log(title = "专项检查类型", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody PtCheckType ptCheckType) {
        return toAjax(ptCheckTypeService.insertPtCheckType(ptCheckType));
    }

    /**
     * 新增专项检查类型
     */
    @PreAuthorize("@ss.hasPermi('patrol:checkType:add')")
    @Log(title = "专项检查类型", businessType = BusinessType.INSERT)
    @PostMapping("/addCheck")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult addCheck(MultipartFile file, @RequestParam("checkName") String checkName, @RequestParam("dateScope") Date[] dateScope, @RequestParam("schoolsKey") Long[] schoolsKey) throws Exception {
        if (StringUtils.isEmpty(checkName)) {
            throw new CustomException("请输入有效检查名称");
        }
        if (dateScope.length != 2) {
            throw new CustomException("请选择有效检查日期范围");
        }
        if (schoolsKey == null || schoolsKey.length == 0) {
            throw new CustomException("请选择检查学校");
        }
        ExcelUtil<PtCheckQuestion> util = new ExcelUtil<>(PtCheckQuestion.class);
        List<PtCheckQuestion> questionList = util.importExcel(file.getInputStream());
        if (questionList.isEmpty()) {
            throw new CustomException("问题文件有误，请按模板进行填写");
        }
        PtCheckType ptCheckType = new PtCheckType();
        ptCheckType.setCheckName(checkName);
        ptCheckType.setAnswerStartDate(dateScope[0]);
        ptCheckType.setAnswerEndDate(dateScope[1]);
        int i = ptCheckTypeService.insertPtCheckType(ptCheckType);
        for (Long schoolItem : schoolsKey) {
            PtCheckRecord ptCheckRecord = new PtCheckRecord();
            ptCheckRecord.setCheckId(ptCheckType.getId());
            ptCheckRecord.setSchoolId(schoolItem);
            ptCheckRecordService.insertPtCheckRecord(ptCheckRecord);
            for (PtCheckQuestion question : questionList) {
                PtCheckAnswer ptCheckAnswer = new PtCheckAnswer();
                ptCheckAnswer.setCheckRecordId(ptCheckRecord.getId());
                ptCheckAnswer.setQuestionName(question.getQuestionName());
                ptCheckAnswerService.insertPtCheckAnswer(ptCheckAnswer);
            }
        }
        return toAjax(i);
    }

    /**
     * 修改专项检查类型
     */
    @PreAuthorize("@ss.hasPermi('patrol:checkType:edit')")
    @Log(title = "专项检查类型", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody PtCheckType ptCheckType) {
        return toAjax(ptCheckTypeService.updatePtCheckType(ptCheckType));
    }

    /**
     * 删除专项检查类型
     */
    @PreAuthorize("@ss.hasPermi('patrol:checkType:remove')")
    @Log(title = "专项检查类型", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(ptCheckTypeService.deletePtCheckTypeByIds(ids));
    }
}
